﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using Mono.Data.Sqlite;
using System.Data;
using System.Runtime.InteropServices;

public class QuestionMgr : MonoBehaviour {
    public static QuestionMgr s_Instance;
    public ChooseQuestionType m_ChooseQuestionType;
    public Text m_QuestionStemText;
    public Text m_IDText;
    public Dropdown m_TypeDropdown,m_OptionCountDropDown;
    public List<Option> m_OptionList = new List<Option>();
    public List<OneQuestion> m_ExistQuestionList = new List<OneQuestion>();
    public OneQuestion m_OneQuestionPrefab;
    public Transform m_QuestionListContent;
    public Image m_InputImg;

    public string m_QuestionStem;
    public int m_ID;
    public int m_Type;
    public string m_ImgPath;
    private OneQuestion m_questionNow;
	// Use this for initialization
	void Awake () {
        s_Instance = this;
	}
    private void Start() {
        OnClickFresh();
    }

    public void GetFilePath(string path) {
        m_ImgPath = path;
    }
	
    public void OnClickConfirm() {
        m_QuestionStem = m_QuestionStemText.text;
        m_ID = int.Parse(m_IDText.text);
        m_Type = m_TypeDropdown.value;
        if (IsFormCorrect()) {
            string cmd = "select * from QUESTION_TABLE where ID = "+m_ID.ToString();
            SqliteDataReader reader = SQLManager.s_Instance.ExecuteSQLCommand(cmd);
            if (reader != null) {
                DataTable dataTable = new DataTable();
                dataTable.Load(reader);
                if (dataTable.Rows.Count > 0) {//已存在试题，修改
                    string cmd1 = "UPDATE QUESTION_TABLE SET " +
                        "TYPE = '" + m_Type.ToString() + "'," +
                        "STEM = '" + m_QuestionStem + "'," +
                        "Pic_Path = '" + m_ImgPath + "'" +
                        "WHERE ID = " + m_ID.ToString();
                    SQLManager.s_Instance.ExecuteSQLCommand(cmd1);
                    string cmd2 = "DELETE FROM OPTION_TABLE WHERE QID = " + m_ID.ToString();
                    SQLManager.s_Instance.ExecuteSQLCommand(cmd2);
                } else {                        //不存在试题，添加
                    InsertQuestion();
                }
                foreach (var item in m_OptionList) {
                    int i = 0;
                    if (item.m_IsCorrect) {
                        i = 1;
                    }
                    InsertOption(item.m_OptionContentText.text, i, item.m_Score,item.m_JumpID);
                }
            }
            reader.Close();
        }
        OnClickFresh();

    }
    public void OnClickFresh() {
        string cmd = "select * from QUESTION_TABLE ORDER BY ID";
        SqliteDataReader reader = SQLManager.s_Instance.ExecuteSQLCommand(cmd);
        for(int i = 0; i < m_QuestionListContent.childCount; i++) {
            m_ExistQuestionList.Clear();
            Destroy(m_QuestionListContent.GetChild(i).gameObject);
        }
        if (reader != null) {
            DataTable dataTable = new DataTable();
            dataTable.Load(reader);
            for(int i = 0; i < dataTable.Rows.Count; i++) {
                string num = dataTable.Rows[i]["ID"].ToString();
                string stem = dataTable.Rows[i]["Stem"].ToString();
                OneQuestion oneQuestion = Instantiate(m_OneQuestionPrefab) as OneQuestion;
                oneQuestion.Init(num,stem);
                oneQuestion.transform.SetParent(m_QuestionListContent);
                oneQuestion.transform.localScale = new Vector3(1f,1f,1f);
                m_ExistQuestionList.Add(oneQuestion);
            }
            reader.Close();
        }
    }
    public void OnCickOneQuestion(OneQuestion oneQuestion) {
        foreach(var item in m_ExistQuestionList) {
            item.SetState(false);
        }
        oneQuestion.SetState(true);
        m_questionNow = oneQuestion;
    }
    public void OnClickDelete() {
        string number = m_questionNow.m_NumberText.text.Replace("题目", "").Replace(":", "");
        string cmd = "delete from OPTION_TABLE WHERE QID = " + number;
        SQLManager.s_Instance.ExecuteSQLCommand(cmd);
        cmd = "delete from QUESTION_TABLE WHERE ID = " + number;
        SQLManager.s_Instance.ExecuteSQLCommand(cmd);
        OnClickFresh();
        m_questionNow = null;
    }
    public void OnClickLoadQuestion() {
        string number = m_questionNow.m_NumberText.text.Replace("题目", "").Replace(":", "");
        string cmd = "select * from QUESTION_TABLE WHERE ID =" + number;
        SqliteDataReader reader = SQLManager.s_Instance.ExecuteSQLCommand(cmd);
        if (reader != null) {
            DataTable dataTable = new DataTable();
            dataTable.Load(reader);
            reader.Close();
            if (dataTable.Rows.Count > 0) {
                m_QuestionStemText.GetComponentInParent<InputField>().text = dataTable.Rows[0]["Stem"].ToString();
                m_IDText.GetComponentInParent<InputField>().text = dataTable.Rows[0]["ID"].ToString();
                int type = (int)dataTable.Rows[0]["Type"];
                m_ChooseQuestionType.Reset();
                m_ChooseQuestionType.OnTypeDropDownValueChange(type);
                m_ChooseQuestionType.GetComponent<Dropdown>().value = type;
                string imgpath = dataTable.Rows[0]["Pic_Path"].ToString();
                StartCoroutine(Load(imgpath));

                if (type != 3) {
                    string cmd1 = "select * from OPTION_TABLE WHERE QID = " + number;
                    SqliteDataReader reader1 = SQLManager.s_Instance.ExecuteSQLCommand(cmd1);
                    if (reader1 != null) {
                        DataTable dataTable1 = new DataTable();
                        dataTable1.Load(reader1);
                        m_OptionCountDropDown.value = 0;
                        m_OptionCountDropDown.value = dataTable1.Rows.Count - 1;
                        for (int i = 0; i < dataTable1.Rows.Count; i++) {
                            int isright = (int)dataTable1.Rows[i]["IsRight"];
                            int score = (int)dataTable1.Rows[i]["Score"];
                            string stem = dataTable1.Rows[i]["Stem"].ToString();
                            string jumpid = dataTable1.Rows[i]["Jump_ID"].ToString();
                            m_ChooseQuestionType.ChangeContentByIndex(i, isright, score, stem, jumpid);
                        }
                        reader1.Close();
                    }
                }
                
            }
        }
    }
    public void OnClcikHome() {
        SceneManager.LoadScene("Scene");
    }
    bool IsFormCorrect() {
        if (m_ID <= 0) {
            print("ID错误");
            return false;//ID错误
        }
        bool flag = false;
        foreach(var item in m_OptionList) {
            if (item.m_IsCorrect) {
                flag = true;
            }
        }
        if(m_Type == 3) {
            flag = true;
        }
        if (!flag) {
            print("未选择正确答案");
            return false;//未选择正确答案
        }
        //string cmd = "select * from QUESTION_TABLE where ID = " + m_ID.ToString();
        //SqliteDataReader reader = SQLManager.s_Instance.ExecuteSQLCommand(cmd);
        //if (reader != null) {
        //    DataTable dataTable = new DataTable();
        //    dataTable.Load(reader);
        //    if (dataTable.Rows.Count > 0) {
        //        print("该编号试题已存在");
        //        return false;//该编号试题已存在
        //    }
        //} else {
        //    return false;
        //}
        return true;
    }
    void InsertQuestion() {
        //string cmddelete = "DELETE FROM OPTION_TABLE WHERE QID = " + m_ID.ToString();
        //SQLManager.s_Instance.ExecuteSQLCommand(cmddelete);
        string cmd = "INSERT INTO QUESTION_TABLE VALUES ('" + 
            m_ID.ToString() + "','" + 
            m_Type.ToString() + "','" + 
            m_QuestionStem + "','" + 
            m_ImgPath+"')" ;
        SQLManager.s_Instance.ExecuteSQLCommand(cmd);
    }
    void InsertOption(string stem,int isRight,int Score,int jumpID) {
        string cmd =
            "INSERT INTO OPTION_TABLE ('" +
                        "QID" + "','" +
                        "Stem" + "','" +
                        "IsRight" + "','" +
                        "Jump_ID" + "','" +
                        "Score" + "') " +
                        "VALUES ('" +
            m_ID.ToString() + "','" +
            stem + "','" +
            isRight.ToString() + "','" +
            jumpID.ToString() + "','" +
            Score.ToString() + "')";
        SQLManager.s_Instance.ExecuteSQLCommand(cmd);
    }

    public void OnClickClearImg() {
        GetFilePath("");
        m_InputImg.sprite = null;
    }

    public void OnClickChooseFile() {
        OpenFileName openFileName = new OpenFileName();

        openFileName.structSize = Marshal.SizeOf(openFileName);

        //openFileName.filter = "Excel文件(*.xlsx)\0*.xlsx";

        openFileName.file = new string(new char[256]);

        openFileName.maxFile = openFileName.file.Length;

        openFileName.fileTitle = new string(new char[64]);

        openFileName.filter = "图片文件(*.jpg*.png)\0*.jpg;*.png";

        openFileName.maxFileTitle = openFileName.fileTitle.Length;

        openFileName.initialDir = Application.streamingAssetsPath.Replace('/', '\\');//默认路径

        openFileName.title = "窗口标题";

        openFileName.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000008;

        if (LocalDialog.GetOpenFileName(openFileName)) {
            LoadPicture(openFileName.file);
        }
    }

    void LoadPicture(string path) {
        if (path.Length < 1) {
            return;
        }
        GetFilePath(path);
        StartCoroutine(Load(path));
    }
    IEnumerator Load(string path) {
        WWW www = new WWW("file:///" + path);
        yield return www;

        while (!www.isDone) {

        }
        if (www.error != null) {
            print(www.error);
            m_InputImg.sprite = null;
        } else {
            Texture2D texture = www.texture;
            Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
            if (texture.width > texture.height) {
                m_InputImg.rectTransform.sizeDelta = new Vector2(649.4f, (float)texture.height/ (float)texture.width* 357.8f);
            } else {
                m_InputImg.rectTransform.sizeDelta = new Vector2((float)texture.width / (float)texture.height * 649.4f, 357.8f);
            }
            m_InputImg.sprite = sprite;
        }

    }
}
